namespace AltNetUK.Models.Inputs
{
    using System;
    using System.Globalization;
    using System.Text.RegularExpressions;

    public class RegexValidator : IValidateText
    {
        private Regex _expression;

        public RegexValidator(string pattern, bool isMatch)
            : this(new Regex(pattern), isMatch)
        {
        }

        public RegexValidator(Regex expression, bool isMatch)
        {
            this.Expression = expression;
            this.IsMatch = isMatch;
        }

        public Regex Expression
        {
            get
            {
                return this._expression;
            }

            set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }

                this._expression = value;
            }
        }

        public bool IsMatch
        {
            get;
            set;
        }

        public virtual ValidationResult Validate(string text)
        {
            ValidationResult result = new ValidationResult();

            if (string.IsNullOrEmpty(text))
            {
                result.Errors.Add(string.Format(CultureInfo.InvariantCulture, "is required"));
            }
            else
            {
                if (this.IsMatch != this.Expression.IsMatch(text))
                {
                    result.Errors.Add(string.Format(CultureInfo.InvariantCulture, "does not appear to be valid"));
                }
            }

            return result;
        }
    }
}